package com.snapan.controller;

import com.snapan.entity.FileBase;
import com.snapan.service.FileBaseService;
import com.snapan.service.PdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/pdf")
public class PdfController {

    @Autowired
    private PdfService pdfService;

    @Autowired
    private FileBaseService fileBaseService;

    /**
     * 以二进制流返回 PDF，用于前端 pdf.js 加载
     */
    @GetMapping("/stream/{fileId}")
    public ResponseEntity<byte[]> streamPdf(@PathVariable Long fileId) throws Exception {
        FileBase fb = fileBaseService.getById(fileId);
        if (fb == null) {
            return ResponseEntity.notFound().build();
        }
        File f = pdfService.resolvePhysicalFile(fb.getFilePath());
        if (!f.exists()) {
            return ResponseEntity.notFound().build();
        }
        byte[] bytes = Files.readAllBytes(f.toPath());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        return ResponseEntity.ok()
                .headers(headers)
                .body(bytes);
    }

    /**
     * 保存编辑后的 PDF（另存为新文件）
     * 前端上传一个完整的 PDF 文件（multipart/form-data），并传原文件ID以便保留路径结构等
     */
    @PostMapping("/save")
    public Map<String, Object> saveEditedPdf(@RequestParam("originalFileId") Long originalFileId,
                                             @RequestParam("file") MultipartFile file,
                                             @RequestParam(value = "userId", required = false) Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Long newFileBaseId = pdfService.saveAsNewFile(originalFileId, file, userId);
            result.put("success", true);
            result.put("message", "已保存为新文件");
            result.put("fileId", newFileBaseId);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "保存失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 可选：上传图片接口（如果前端想单独上传图片）
     */
    @PostMapping("/upload-image")
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile image,
                                           @RequestParam(value = "userId", required = false) Integer userId) {
        Map<String, Object> res = new HashMap<>();
        try {
            String savedPath = pdfService.saveImageTemp(image);
            res.put("success", true);
            res.put("path", savedPath);
        } catch (Exception e) {
            res.put("success", false);
            res.put("message", e.getMessage());
        }
        return res;
    }
}
